<?php


namespace WechatPayment\tools;


class Encryption
{
    protected $service_no;
    protected $mch_id;
    protected $apiclient_key_path;
    public function __construct($array)
    {
        if(count($array)){
            $this->service_no = $array['service_no'];
            $this->mch_id = $array['mch_id'];
            $this->apiclient_key_path = $array['apiclient_key'];
        }
    }

    function get_signature($url,$method, $data,$str,$time)
    {
        $method = strtoupper($method);
        if ($method == 'GET')
        {
            $url = $url."?".http_build_query($data);
        }
        $signature = $method . "\n"
            . $url . "\n"
            . $time . "\n"
            . $str . "\n"
            //POST方式需要数据
            . ($method == "POST" ? json_encode($data) : "")
            . "\n";
        //读取文件资源
        $mch_private_key = $this->red_file($this->apiclient_key_path);
        //加密
        openssl_sign($signature, $raw_sign, $mch_private_key, "sha256WithRSAEncryption");
        //二次加密
        $string = base64_encode($raw_sign);
        //商户序列号
        $serial_no = $this->service_no;
        $sign = sprintf('mchid="%s",nonce_str="%s",timestamp="%d",serial_no="%s",signature="%s"', $this->mch_id, $str, $time, $serial_no, $string);
        return $sign;
    }

    /**
     * 读取文件内容
     * @param $path
     * @return bool|string
     */
    public function red_file($path)
    {
        return openssl_get_privatekey(file_get_contents($path));
    }


    public function get_sign_2($package,$appkey){
        //获取商户号
        $queryString['mch_id'] = $this->mch_id;
        //扩展字符串
        $queryString['package'] = $package;
        //生成签名时间戳，单位秒
        $queryString['timestamp'] = strval(time());
        $rand = new RandomStr();
        //签名随机字符串 数字大小写字母 长度不超过32位
        $queryString['nonce_str'] = $rand->randomStr(32);
        //签名方式
        $queryString['sign_type'] = 'HMAC-SHA256';
//        $key = $this->api_key;//注：key为商户平台设置的密钥key
        $WxNewEncrypt = new WxNewEncrypt(['app_key'=>$appkey]);
        //签名
        $queryString['sign'] = $WxNewEncrypt->SetSign($queryString);

        return $queryString;
    }
}